<?php
header('Content-Type: text/html; charset=utf-8');
error_reporting(E_ALL);
set_time_limit(0);
include_once dirname(dirname(dirname(dirname(dirname(__FILE__)))))."/common.php";
\ns_core\m_load::load("ns_core.m_config");
\ns_core\m_load::load("ns_core.m_file");
\ns_core\m_load::load_old("nn_logic/sync_category/sync_category.class.php");
class category_sync
{
    public $str_category_sync='';
    
    public $int_analyze_count = 120;
    
    public function __construct()
    {
        $this->str_category_sync = dirname(dirname(dirname(dirname(dirname(dirname(__FILE__)))))).'/data/temp/category_sync/';
    }
    
    public function get_files()
    {
        $result_file = m_file::get_files_v2($this->str_category_sync);
        if(!is_array($result_file) || empty($result_file))
        {
            return $result_file;
        }

        $str_exe = evn::get("php_execute_path") . ' -f ' . dirname(__FILE__) . '/category_sync.php ';
        foreach ($result_file as $value)
        {
            $arr_pathinfo = pathinfo($value['path']);
            $filename = (isset($arr_pathinfo['filename']) && strlen($arr_pathinfo['filename'])>0) ? trim($arr_pathinfo['filename']) : '';
            if(strlen($filename)<1 || strpos($filename, '_') === FALSE)
            {
                continue;
            }
            $str_avg = base64_encode($value['path']);
            if (substr(php_uname(), 0, 7) != "Windows")
            {
                //LINUX下执行
                $str_order = "{$str_exe}  {$str_avg} > /dev/null &";
            }
            else
            {
                //windows下执行
                $str_order = "{$str_exe}  {$str_avg} ";
            }
            usleep(50000);
//             var_dump($str_order);
            exec($str_order);
        }
    }
    
    public function exec_files($file_url)
    {
        $file_url = base64_decode($file_url);
        if(!file_exists($file_url))
        {
            return m_config::return_data(1,"文件不存在{$file_url}");
        }
        $result = $this->analyze_file($file_url);
    }
    
    
    /**
     * 分析片源文件  遍历
     * @param unknown $file_path
     */
    public function analyze_file($file_path)
    {
        $data_file = fopen($file_path, 'r');
        $locked = flock($data_file, LOCK_EX + LOCK_NB);
        $count = 0;
        $is_left_flag = true;
        while (!feof($data_file))
        {
            $line_item = fgets($data_file);
            if (!$line_item)
            {
                continue;
            }
            $line_item = trim($line_item);
            if(strlen($line_item) <1)
            {
                continue;
            }
            $count++;
            if($count >$this->int_analyze_count)
            {
                ob_start();
                fpassthru($data_file);
                $is_left_flag = false;
                break;
            }
            $this->indert_data($line_item);
        }
        flock($data_file, LOCK_EX + LOCK_NB);
        fclose($data_file);
        $left_content = $is_left_flag ? "" : ob_get_clean();
        if(strlen($left_content) >0)
        {
            @file_put_contents($file_path, $left_content);
        }
        else
        {
            @unlink($file_path);
        }
        return self::return_data(0,"Ok");
    }
    
    public function indert_data($data)
    {
        $data = iconv(mb_detect_encoding($data, array('GBK', 'UTF-8', 'UTF-16LE', 'UTF-16BE', 'ISO-8859-1')), 'UTF-8',$data );
        $data = explode('|', $data);
        $nns_category_id = isset($data['0']) ? $data['0'] : '';
        $nns_parent_id = isset($data['1']) ? $data['1'] : '';
        $nns_name = isset($data['2']) ? $data['2'] : '';
        $nns_hierarchy = isset($data['3']) ? $data['3'] : '';
        $nns_cms_asset_id = 'vod';
        if($nns_category_id=='4447')
        {
            $nns_parent_id = '0';
        }
        if(strlen($nns_category_id) <1)
        {
            return m_config::return_data(1,"nns_category_id为空");
        }
        if(strlen($nns_parent_id) <1)
        {
            return m_config::return_data(1,"nns_parent_id为空");
        }
        if(strlen($nns_name) <1)
        {
            return m_config::return_data(1,"nns_name为空");
        }
        if(strlen($nns_hierarchy) <1)
        {
            return m_config::return_data(1,"nns_hierarchy为空");
        }
        $arr_insert = array(
            'nns_id'=>md5($nns_category_id."|".$nns_parent_id."|".$nns_hierarchy),
            'nns_category_id'=>$nns_category_id,
            'nns_parent_id'=>$nns_parent_id,
            'nns_name'=>$nns_name,
            'nns_hierarchy'=>$nns_hierarchy,
            'nns_cms_asset_id'=>$nns_cms_asset_id,
            'nns_cms_category_id'=>'',
            'nns_cms_category_name'=>'',
            'nns_third_category_id'=>'',
        );
        $result_query = nl_sync_category::query_by_condition(m_config::get_dc(), array('nns_id'=>$arr_insert['nns_id']));
        if($result_query['ret'] !=0)
        {
            return $result_query;
        }
        if(isset($result_query['data_info'][0]) && is_array($result_query['data_info'][0]) && !empty($result_query['data_info'][0]))
        {
            $result_query = $result_query['data_info'][0];
            if($result_query['nns_name'] !=$arr_insert['nns_name'])
            {
                $nns_id = $arr_insert['nns_id'];
                unset($arr_insert['nns_id']);
                $result= nl_sync_category::edit(m_config::get_dc(), $arr_insert,$nns_id);
                if($result['ret'] !=0)
                {
                    return $result;
                }
                $sql = "update nns_sync_category set nns_cms_category_name='' where nns_third_category_id like '%/{$nns_category_id}/%'";
                return nl_sync_category::edit_sql(m_config::get_dc(),$sql);
            }
        }
        return nl_sync_category::add(m_config::get_dc(), $arr_insert);
    }
    
    
    public function __destruct()
    {
        
    }
}


if(isset($_SERVER['argv'][1]) && !empty($_SERVER['argv'][1]))
{
    $obj_category_sync = new category_sync();
    $result = $obj_category_sync->exec_files($_SERVER['argv'][1]);
}
else
{
    $obj_category_sync = new category_sync();
    $result = $obj_category_sync->get_files();
}
echo json_encode($result);